<?php
namespace app\manage\controller;
use think\Db;

class RebateApply extends Base
{
    public function index(){
        if(request()->isAjax()){
            $gameId = input('game_id');
            $myOrderId = input('my_order_id');
            $myUserName = input('my_user_name');
            $roleId = input('role_id');
            $roleName = input('role_name');
            $date = explodeTime(input('date'));
            $startDate = $date['start_time'];
            $endDate = $date['end_time'];

            if(empty($myOrderId)){
                return $this->layTable();
            }

            $dateRange = model('CommonOption')->where('id=112')->value('value');

            //超过返利期限处理
            if($startDate < $endDate-$dateRange*86400){
                $startDate=$endDate-$dateRange*86400;
            }

            $rebateData = model('RebatedOrder')->getRebateData($gameId,$myUserName,$myOrderId,$roleId,$roleName,$startDate,$endDate);

            $gameIdName = changeValKey('ViewGameManage', 'game_id', 'game_name');
            $selectChannel = model('ViewChannel')->select();
            $channelIdName = [];
            foreach ($selectChannel as $v) {
                $channelIdName[$v['channel_id'].'_'.$v['cps_id']] = $v['channel_name'].'-'.$v['cps_name'];
            }

            //数据过滤
            $i = 0;
            $data = [];
            foreach ($rebateData as $v) {
                foreach ($v as $v1) {
                    foreach ($v1 as $v2) {
                        foreach ($v2 as $date => $v3) {
                            $data[$i] = [
                                'toberebate_gamecoin' => $v3['sum']['toberebate_gamecoin'],
                                'date' => $date,
                            ];

                            $data[$i]['datas']['count_sum'] = $v3['sum'];

                            if($v3['sum']['toberebate_gamecoin'] == 0){
                                $disabled = 'disabled';
                            }else{
                                $disabled = '';
                            }

                            $data[$i]['button'] = "<button class='btn btn-info btn-sm view' style='margin-right:5px;'><i class='fa fa-search'></i> 查看</button> <button class='btn btn-info btn-sm rebate' {$disabled}><i class='fa fa-refresh'></i> 返利</button>";

                            foreach ($v3['rule'] as $ruleNum => $v4) {
                                $data[$i]['datas'][$ruleNum]['sum'] = $v4['sum'];

                                foreach ($v4['order'] as $orderNum => $v5) {
                                    $data[$i]['datas'][$ruleNum][$orderNum] = [
                                        'my_order_id' => $v5['orderid'],
                                        'channel_id' => $v5['channelid'],
                                        'channel_name' => $channelIdName[ $v5['channelid'] ],
                                        'game_id' => $v5['gameid'],
                                        'game_name' => $gameIdName[ $v5['gameid'] ],
                                        'server_id' => $v5['serverid'],
                                        'server_name' => $v5['servername'],
                                        'my_user_id' => $v5['userid'],
                                        'my_user_name' => $v5['loginname'],
                                        'role_id' => $v5['roleid'],
                                        'role_name' => $v5['rolename'],
                                        'total_price' => round($v5['amount'], 2),
                                        'ratio' => $v5['ratio'],
                                        'game_coin' => $v5['gamecoin'],
                                        'pay_time' => date('Y-m-d H:i:s', $v5['paytime']),
                                        'is_rebate' => $v5['isrebate'],
                                        'rule_id' => $v5['ruleid'],
                                        'rule' => $v5['rule'],
                                        'rebate_gamecoin' => $v5['rebate_gamecoin'],
                                        'apply_id' => $v5['applyid'],
                                        'apply_time' => $v5['applytime'],
                                    ];

                                    $data[$i]['game_name'] = $v5['gameid'] . '：' . $gameIdName[ $v5['gameid'] ];
                                    $data[$i]['server_name'] = $v5['serverid'] . '：' . $v5['servername'];
                                    $data[$i]['role_name'] = $v5['roleid'] . '：'. $v5['rolename'];
                                    $data[$i]['my_user_name'] = $v5['userid'] . '：' . $v5['loginname'];
                                    $data[$i]['game_id'] = $v5['gameid'];
                                    $data[$i]['server_id'] = $v5['serverid'];
                                    $data[$i]['role_id'] = $v5['roleid'];
                                    $data[$i]['my_user_id'] = $v5['userid'];
                                }
                            }
                            $i++;
                        }
                    }
                }
            }
            $this->layTable(0, '申请返利列表', $data, count($data));

        }else{
            $dateRange = model('CommonOption')->where('id', 112)->value('value');
            $date = date('Y-m-d', time()-(86400*$dateRange)).' - '.date('Y-m-d', time());
            return view('', ['dateRange'=>$dateRange, 'date'=>$date]);
        }
    }

    public function view(){
        return view();
    }

    public function rebate(){
        $myUserId = input('my_user_id');
        $gameId = input('game_id');
        $serverId = input('server_id');
        $roleId = input('role_id');
        $rebateDate = input('date');

        if($rebateDate==''||$myUserId==''||$gameId==''||$serverId==''||$roleId==''){
            $this->layJson(1, '返利日期,用户名,游戏ID,区服ID,角色ID等数据不全');
        }

//        cache(['type'=>'Redis']);
        //cache(['type'=>'Memcache']);
        $cache_key = 'rebate_day_'.strtoupper(md5($myUserId.$gameId.$serverId.$roleId.$rebateDate));
        $rebateData = cache($cache_key);
        cache($cache_key, NULL);

        if(!$rebateData){
            $this->layJson(1, '操作超时，请右键刷新或者重新点击搜索');
        }
        if($rebateData['sum']['toberebate_gamecoin']==0){
            $this->layJson(1, '已经返利过，不允许再次返利');
        }

        $orderList = [];
        $orderSave = [];
        foreach($rebateData['rule'] as $rule){
            foreach($rule['order'] as $order){
                if(empty($order['isrebate'])){
                    $orderList[]=$order['orderid'];
                }
                $order['applyid'] = '';
                $order['applytime'] = time();
                $orderSave[] = $order;
            }
        }

        if(empty($orderList)){
            $this->layJson(1, '未找到相应订单');
        }else{
            ksort($orderList);
            $str='';
            foreach($orderList as $v){
                $str .= $v;
            }
            $applyId = strtoupper(md5($str));
            foreach ($orderSave as $k=>$v) {
                $orderSave[$k]['applyid'] = $applyId;
                unset($orderSave[$k]['ratio']);
                unset($orderSave[$k]['isrebate']);
                unset($orderSave[$k]['ruleid']);
            }
        }

        $data = [
            'applyid' => $applyId,
            'gameid' => $gameId,
            'userid'  => $myUserId,
            'serverid' => $serverId,
            'roleid' => $roleId,
            'total_amount' => intval($rebateData['sum']['total_amount']),//当日充值总额
            'rebate_gamecoin' => $rebateData['sum']['toberebate_gamecoin'],//本次要返的游戏币
            'order_lists' => urlencode(json_encode($orderList)),//涉及的订单列表
            'applytime' => time(),//申请操作提交的时间
            'rebatedate' => strtotime($rebateDate),//返利的日期
        ];

        $res = model('RebatedOrder')->sendGameInfo($data);

        if($res['result']!==1){
            $this->layJson(1, $res['msg']);
        }

        $rs=model('RebatedOrder')->allowField(true)->insertAll($orderSave);
        $saveData['rebate_time'] = time();

        foreach($orderList as $myOrderId){
            $table = get_order_table($myOrderId);
            Db::name($table)->where('my_order_id', $myOrderId)->update(['rebate_time'=>time()]);
        }

        $this->layJson(0, '已审核，可以右键刷新或搜索查看结果');
    }
}